package com.shanpin.shebao.web.module.coupon;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.shanpin.core.constant.EnvConf;
import com.shanpin.core.utils.JodaUtil;
import com.shanpin.shebao.constant.CouponType;
import com.shanpin.shebao.model.ServiceResult;
import com.shanpin.shebao.web.module.coupon.model.Coupon;
import com.shanpin.shebao.web.module.link.LinkService;
import com.shanpin.shebao.web.module.link.model.Link;

/**
 * 现金券控制器
 * @author 品讯科技
 *
 */
@Controller
@RequestMapping("/coupon")
public class CouponController {
	
	public static final String MSG = "errmsg";
	
	@Autowired
	private CouponService couponService;
	@Autowired
	private LinkService linkService;

	/**
	 * 跳转到领券页面 （如果code过期，则重新生成code）
	 * @param coupon_id  优惠券编号
	 * @param channel_id  优惠券渠道编号
	 * @param plusDays  领券链接有效时间
	 * @param channel 领券成功后跳转H5的渠道
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(path="/tolink/{coupon_id}/{channel_id}", method=RequestMethod.GET) 
	public ModelAndView tolink(@PathVariable("coupon_id") String coupon_id, @PathVariable("channel_id") String channel_id,
			Integer plusDays,
			String channel,
			RedirectAttributes redirectAttributes) {
		if(plusDays==null || plusDays<0 || plusDays>30) {
			plusDays = 30;
		}
		//XXX 硬编码
		String url = "http://192.168.1.99/sbw/coupon/tobind/"+coupon_id+"/"+channel_id;
		if(!EnvConf.isProd()) {
			url = "http://192.168.1.99:8500/sbw/coupon/tobind/"+coupon_id+"/"+channel_id;
		}
		
		Link link = linkService.queryByUrl(url);
		Date curDate = new Date();
		String code = null;
		if(link==null || 
				(link.getEnd_date()!=null&&link.getEnd_date().getTime()<curDate.getTime())) {
			//链接不存在或者过期，则重新生成一个链接
			code = UUID.randomUUID().toString().replace("-", "");
			link = new Link();
			link.setUrl(url);
			link.setCode(code);
			
			link.setType(CouponType.FIXED_LIMIT.getKey());  //固定期限券
			link.setMonth_limit(0);	
			link.setEnd_date(JodaUtil.plusDays(curDate, plusDays)); //链接有效时间
			link.setPurpose(3);  		//渠道推广
			link.setShare_limit(1);
			link.setCreate_time(curDate);
			linkService.addLink(link);
		} else {
			code = link.getCode();
		}
		
		ModelAndView mv = new ModelAndView("redirect:/sbw/coupon/tobind/"+coupon_id+"/"+channel_id);
		redirectAttributes.addAttribute("coupon_id", coupon_id);
		redirectAttributes.addAttribute("channel_id", channel_id);
		redirectAttributes.addAttribute("code", code);
		redirectAttributes.addFlashAttribute("channel", channel);
		return mv;
	}

	/**
	 * 跳转到领券页面
	 * @param coupon_id 优惠券编号
	 * @param channel_id 优惠券渠道
	 * @param code 优惠券编码
	 * @param channel 领券后跳转H5的渠道
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(path="/tobind/{coupon_id}/{channel_id}", method=RequestMethod.GET) 
	public ModelAndView tobind(@PathVariable("coupon_id") String coupon_id, @PathVariable("channel_id") String channel_id, 
			String code,
			String channel) {
		ModelAndView mv = new ModelAndView("coupon/index");
		mv.addObject("currentDate", new Date());
		mv.addObject("channel_id", channel_id);
		mv.addObject("code", code);
		mv.addObject("channel", channel);

		if ("2".equals(coupon_id)) {
			mv.addObject(MSG, "不支持此种方式领取[2]");
			return mv;
		}

		//检查券的有效性
		ServiceResult<Coupon> checkCouponResult = couponService.checkCoupon(coupon_id, channel_id);
		if(StringUtil.isNotBlank(checkCouponResult.msg)) {
			mv.addObject(MSG, checkCouponResult.msg);
			return mv;
		}
		Coupon coupon = checkCouponResult.result;
				
		//检查链接有效性
		ServiceResult<Link> checkLinkResult = linkService.checkLink(code);
		if(StringUtil.isNotBlank(checkLinkResult.msg)) {
			mv.addObject(MSG, checkLinkResult.msg);
			return mv;
		}
		Link shareLink = checkLinkResult.result;
		//链接统计点击次数+1 
		//FIXME 并发情况统计可能不正确，数据库update count = count+1
//		shareLink.setCount(shareLink.getCount()+1);
		linkService.updateCount(shareLink.getId());

		mv.addObject("coupon", coupon);
		return mv;
	}

	///////////////////////////// 运营新用户首单专享   //////////////////////
	// 首单专享优惠券领取页面
	@RequestMapping("/shareable/newer") 
	public String toNewCoupon(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		Link shareLink= linkService.queryByCode("ff8080815500cddc0155143c58ec0000");
//		shareLink.setCount(shareLink.getCount() + 1);
		linkService.updateCount(shareLink.getId());
		return "coupon/new_coupon";
	}

	@RequestMapping("/shareable/newer_catched") 
	public String catchedNewCoupon(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		return "coupon/new_coupon2";
	}
	
}
